﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SAKS.IServices;
using System.Web.Security;
using NHibernate;

namespace SAKS.Services
{
    public class FormsAuthenticationServices : IFormsAuthenticationServices
    {

        public void SignIn(string userName, bool createPersistentCookie,IList<string> roles)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("值不可以为空或\"null\".", "userName");
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.Add(FormsAuthentication.Timeout),
                createPersistentCookie,
                roles.Count == 0 ? "" : roles.Aggregate((i, j) => i + "," + j)
                );
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            if (authTicket.IsPersistent)
            {
                authCookie.Expires = authTicket.Expiration;
            }
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}
